package com.sl.crawler.robot.getUrl.selector;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

public class CssSelector {

    private static String getValue(Element element, String attrName) {
        if (StringUtils.isBlank(attrName)) {
            return element.outerHtml();
        } else if ("innerHtml".equalsIgnoreCase(attrName)) {
            return element.html();
        } else if ("text".equalsIgnoreCase(attrName)) {
            return getText(element);
        } else if ("allText".equalsIgnoreCase(attrName)) {
            return element.text();
        } else {
            return element.attr(attrName);
        }
    }

    private static String getText(Element element) {
        StringBuilder sb = new StringBuilder();
        for (Node node : element.childNodes()) {
            if (node instanceof TextNode) {
                TextNode textNode = (TextNode) node;
                sb.append(textNode.text());
            }
        }
        return sb.toString();
    }


    public static List<String> selectList(String html, String cssSelector, String attrName) {
        Document document = Jsoup.parse(html);
        return selectList(document, cssSelector, attrName);
    }


    public static List<String> selectList(Element element, String cssSelector, String attrName) {
        Elements elements = element.select(cssSelector);
        List<String> resultList = new ArrayList<>();
        for (Element childElement : elements) {
            String value = getValue(childElement, attrName);
            resultList.add(value);
        }
        return resultList;
    }


}
